<?php
ArrowController::importModel("org.arrowplatform.model.ArrowDataSource");
ArrowController::importModel("media.MediaFolder");
ArrowController::importModel("media.MediaElement");
ArrowController::importModel("media.MediaTransformationProfile");
ArrowController::importModel("media.MediaElementConnection");
ArrowController::importModel("media.MediaApi");
class ArrowMediaConnectorSingle extends ArrowTagContainer{
	
	protected $dataSource;
	
	private $field = null;
	private $currFile = null;
	private $currDirId = null;
	
	private $folder = null;
	private $parentFolder = null;
	
	public function configure(){
		
		$this->addProperties(array(
			"state" => "list",
			"model" => null,
			"key" => null,
			"presentation" => "list",
			"files" => "jpg;png",
			"transformation" => '',
			"single" => false,
			"title" => "Tytuł",
			"name" => "noname",
			"parentSystemName" => false,
			"targetSystemName" => false,
			"targetName" => false,
			"subFolderName" => false
		));
		$this->addRequiredProperties(array( "model", "key"));
		$this->addStateProperties(array("state", "selected"));
		$this->setContentCodeKept(true);
		
	}
	
	public function init(){
		//$this->registerJs( get_class($this), dirname(__FILE__)."/ArrowMediaConnector.js", ".ctrl-media-connector");
		$key = $this->getProperty("key");
		$model = $this->getProperty("model");
		ArrowController::importModel($model);
		if( $key ){
			
			$targetSysName = $this->getProperty("targetSystemName");
			$look = $targetSysName?$targetSysName:$model;
			$criteria = new Criteria();
			$criteria->addCondition( MediaFolder::F_SYSTEM_NAME,$look  );
			$folder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
			if(!empty($folder)){
				$this->folder = $folder[0];
			}else{
				
		 
			//Target folder creation
				$container = MediaApi::getSystemFolder();
				$parentSystemName = $this->getProperty("parentSystemName");
				if( $parentSystemName ){
					$criteria = new Criteria();
					$criteria->addCondition( MediaFolder::F_SYSTEM_NAME, $parentSystemName );
					$logicalParent = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
					if(empty($logicalParent)){
						$container = MediaApi::createFolder( $container->getPKey(), $parentSystemName, $parentSystemName );
					}else{
						$container = $logicalParent[0];
					}
				}
				
				$name = $this->getProperty("targetName")?$this->getProperty("targetName"):"Container_{$look}";
				
				
				$criteria = new Criteria();
				$criteria->addCondition( MediaFolder::F_SYSTEM_NAME,$look  );
				$folder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
				if(empty($folder)){
					
					$this->folder = MediaApi::createFolder( $container->getPKey(), $name, $look );
				}else{
					$this->folder = $folder[0];
				}
			}
			
			$this->parentFolder = $this->folder;
				
			$subFolderName = $this->getProperty("subFolderName");
			if(!empty($subFolderName)){
				$criteria = new Criteria();
				$criteria->addCondition( MediaFolder::F_NAME, StringHelper::toValidFilesystemName( $subFolderName ) );
				$criteria->addCondition( MediaFolder::F_PARENT_ID, $this->folder->getPKey() );
				$subFolder = MediaFolder::getByCriteria( $criteria, MediaFolder::TCLASS );
				if(empty($subFolder)){
					$this->folder = MediaApi::createFolder( $this->folder->getPKey(), $subFolderName );
				}else{
					$this->folder = $subFolder[0];
				}
			}
			//-----------------------
			
			$critConnection = new Criteria("media.MediaElementConnection");
			$critConnection->addCondition( MediaElementConnection::F_MODEL, $model );
			$critConnection->addCondition( MediaElementConnection::F_OBJECT_ID, $key );
			$critConnection->addCondition( MediaElementConnection::F_NAME, $this->getProperty("name") );
			$critElement = new Criteria("media.MediaElement");
			$critElement->setLimit(0, 1);
			$criteria = new ArrowOrmJoinCriteria(array($critElement, $critConnection));
			$result = MediaElement::getByCriteria( $criteria, MediaElement::TCLASS );
			if(!empty($result))
				$this->currFile = $result[0];
		}
	}
	
	public function generateBlockStart(){
		$str ='<div class="'.self::CTRL_NAMESPACE.'-media-connector" >';
		$key = $this->getProperty("key");
		if(empty($key)){
			$str.="Wymagany zapis obiektu aby go edytować</div>";
			return $str;
		}

		$content=$this->generateAddForm();
		$str.= '<div class="'.self::CTRL_NAMESPACE.'-media-connector-content" >';
		$str.=$content;
		$str.= '</div>';
		$str.="</div>";
		return $str; 
	}
	public function generateBlockEnd(){
		return "";
	}
	
	public function generateAddForm(){
		
		$model = $this->getProperty("model");
		$key = $this->getProperty("key");
		$name = $this->getProperty("name");
		
		$folderId = $this->folder->getPKey();
		$transformation = "0";
		
		if( $this->getProperty("transformation") ){
			$criteria = new Criteria();
			$criteria->addCondition(MediaTransformationProfile::F_SYSTEM_NAME, $this->getProperty("transformation"));
			$profile = MediaTransformationProfile::getByCriteria( $criteria, MediaTransformationProfile::TCLASS );
			if( !empty($profile) ){
				$profile = $profile[0];
				$transformation = $profile->getPKey();
			}else{
				throw new ArrowException(array("msg" => "Transformation not found", "transformation" => $this->getProperty("transformation")));
			}
		}
		
		$pFiles = $this->getProperty("files");
		if(empty($pFiles)){
			$files = "*.*;";
			$filesDesc = "Pliki";
		}else{
			$tmp = explode( ";", $this->getProperty("files"));
			$files = "";
			foreach($tmp as $ex)
				$files.="*.".$ex.";";
			$filesDesc = "Pliki: ". $files;
		}
		
		

		
		$res = ArrowResources::getDefault(ArrowController::$activeProject);
		$uploadify = $res->getResource("/js/jquery/uploadify/jquery.uploadify.v2.1.0.min.js")->getRelativePath();
		$uploadifyCss = $res->getResource("/js/jquery/uploadify/uploadify.css")->getRelativePath();
		$swfObject = $res->getResource("/js/swfobject/swfobject.js")->getRelativePath();
		$swf = $res->getResource("/js/jquery/uploadify/uploadify.swf")->getRelativePath();
		$deleteIcon = $res->getResource("/graphic/administration/icons/delete.gif")->getRelativePath();
		
		$bean =  ArrowTemplateLinker::getDefault()->generateBeanLink( array( "path" => "/controller::save" ), true);
		
		$stateChangeLink = $this->getStateChangeLink(array("state" => "list"),true);
		
		$ajaxCont = $this->getParent("ArrowCtrlAjax")->getId();
		
		$fileName = "";
		$preview = "";
		if($this->currFile){
			$fileName = $this->currFile["name"];

			$conn = $this->currFile->getRel("MediaElementConnection");
			if(!empty($conn))
				$conn = $conn[0]->getPKey();
			else
				$conn = 0;
			
			$deleteOldLink = ArrowTemplateLinker::getDefault()->generateBeanLink(array(
				"path" => "/controller::actionRouter",
				"action" => "delete",
				"model" => "media.MediaElement",
				"key" => $this->currFile->getPKey(),
				"_htmlAmp" => 0
			));
			
			if($this->currFile->isImage())
				$preview = '<img src="'.$this->currFile->getSystemMiniature().'" />';
				
			//@todo - zoptymalizować
			$obj = Persistent::getByKey($this->getProperty("key"), ArrowModel::getModelClass( $this->getProperty("model")));
			MediaApi::prepareMedia( array($obj) );
			
			$data = $obj["media"][$name];
			$links = "";
			if(!empty($data[0]["path"])){
				$fileName = "<a target=\"blank\" class=\"ctrl-media-preview\" href=\"{$data[0]["path"]}\">{$fileName}</a>";
			}
			
			if(isset($data[0]["verPath"])){
				foreach($data[0]["verPath"] as $verName => $path){
					$links.= "<a target=\"blank\" class=\"ctrl-media-preview\" href=\"{$path}\">{$data[0]["verNames"][$verName]}</a><br />";
				}
			}
			
			$deleteOld = "<a href=\"#\" onclick=\"ctrlMediaDelete(this, '{$this->currFile->getPKey()}', '$conn');\" \">[usuń]</a>";
		}else{
			$links = "";
			$deleteOldLink = "";
			$deleteOld = "";
			
		}
		
		$rand = rand( 1, 100000);
		
    $action = $this->addNode("ui", "action", array( 
      'type' => 'dialog', 'name' => 'Wybierz z istniejących',
      'width' => 900, 'height' => 600,  
      'template' => "/mediafolder::popupBrowser" ,'id' => 'create'
     ));
    $action->addNode('ui', 'param', array('name' => 'model', 'value' => $this->getProperty("model") ));
    $action->addNode('ui', 'param', array('name' => 'key', 'value' => $this->getProperty("key") ));
    $action->addNode('ui', 'param', array('name' => 'ctrlId', 'value' => $this->getParent()->getId() ));
    $action->addNode('ui', 'param', array('name' => 'name', 'value' => $this->getProperty("name") ));
    $action->addNode('ui', 'param', array('name' => 'delete_old', 'value' => 1 ));
    $action->addNode('ui', 'param', array('name' => 'changeConnection', 'value' => 1 )); 
    $action->addNode('ui', 'param', array('name' => 'root', 'value' => $this->parentFolder->getPKey() ));
    
    
    if( $this->getProperty("transformation") ){
      $criteria = new Criteria();
      $criteria->addCondition(MediaTransformationProfile::F_SYSTEM_NAME, $this->getProperty("transformation"));
      $profile = MediaTransformationProfile::getByCriteria( $criteria, MediaTransformationProfile::TCLASS );
      $action->addNode('ui', 'param', array('name' => 'transformationId', 'value' => $profile[0]->getPKey() ));
    }
    
    $action->init();
    
    $fromMediaFolder = $action->generate();
		
	$sessionId = session_id();
		
$str = <<<HTML
<script type="text/javascript" src="{$uploadify}"></script>
<script type="text/javascript" src="{$swfObject}"></script>
<link rel="stylesheet" type="text/css" href="{$uploadifyCss}" />
<style type="text/css">
	.uploadifyQueueItem{
		width: auto !important;
	}
</style>
<script type="text/javascript">

$(function() {
	$("#file-single{$rand}").uploadify({
		'uploader'       : '{$swf}',
		'script'         : '{$bean}',
		'scriptData'	 : { 
			object: "media.MediaElement", 
			'data[folder_id]': "{$folderId}", 
			"data[transformation_id]": '{$transformation}',
			"connection[model]": '{$model}',
			"connection[key]": '{$key}',
			"connection[name]": '{$name}',
			"connection[delete_old]": '1',
			"connection[direct]": '1',
			"sessionId": '{$sessionId}'
		},
		'cancelImg'      : '{$deleteIcon}',
		'folder'         : 'uploads',
		'queueID'        : 'fileQueue-single{$rand}',
		'buttonText'     : 'Z dysku',
		'width'			 : '78',
		'height'	 	 : '21',
		'auto'           : true,
		'multi'          : false,
		'fileDesc'		 : '{$filesDesc}',
		'fileExt'		 : '{$files}',
		'fileDataName'   : 'file',
		onComplete: function (evt, queueID, fileObj, response)
   		{
   			eval('var res = '+response + ' ;');
   			ArrowResponseReader.read({ response: res });
   		},
   		onAllComplete: function(evt, data){
	   		CtrlAjax.changeState( '{$ajaxCont}', '{$stateChangeLink}' );
   		}
	});
	
});

function ctrlMediaDelete(object, elId, conId) {
	var link = $(object);
	if(!confirm("Czy napewno usunąć element?"))
		return false;
	
	ArrowDataConnector.getObjects(
		'media.MediaElementConnection', 
		{"criteria": "element_id:==:" + elId},
		{},
		function(data){ 
			var target = "connection";
			if(data.length == 1){
				if(confirm("Element nie jest używany nigdzie indziej, usunąć całkowicie?"))
					target = "element";
			}
			
			var model;
			var id;
			if(target == "connection"){
				model = "media.MediaElementConnection";
				id = conId;
			}else{
				model = "media.MediaElement";
				id = elId;
			}
			ArrowDataConnector.deleteObject(model,id, {}, function(){
				CtrlAjax.changeStateVars(link,{},{});
			});
		}
	);
	
	return false;
}

	

$(function(){
	$(".ctrl-media-preview").click(function(){
		window.top.$.nyroModalManual({ url: $(this).attr("href"), zIndexStart: 999999999 });
	});
});
</script>
<table style="width: auto;">
	<tr>
		<td style=" padding: 10px;"><b style="font-size: 16px;">{$this->getProperty("title")}</b> $deleteOld</td>
		<td><input type="file" id="file-single{$rand}" name="file" /></td>
		<td>{$fromMediaFolder}</td>
	</tr>
	<tr>
		<td style="padding: 10px;" colspan="3">
			<div style="font-size: 16px;">{$fileName}</div>
		</td>
	</tr>
	<tr>

		<td align="left">$preview</td>
		<td align="left">$links</td>
	</tr>
	<tr>
		<td colspan="3" style="font-size: 16px;"><div id="fileQueue-single{$rand}" ></div></td>
	</tr>
</table>
HTML;

/*
 * <div style="float: left;  margin-right: 10px; background-color: rgb(84, 83, 84); height: 20px; padding: 5px;">
		<a style="color: white; font-size: 13px; font-weight: bold;" href="{$connectionLink}">Wybierz z istniejących</a>
	</div>
 */
		
		return $str;
	}
	

}
?>
